/*
 * Copyright(C) 2019 FUYUN DATA SERVICES CO.,LTD. - All Rights Reserved
 * Unauthorized copying of this file, via any medium is strictly prohibited
 * Proprietary and confidential
 * 该源代码版权归属福韵数据服务有限公司所有
 * 未经授权，任何人不得复制、泄露、转载、使用，否则将视为侵权
 *
 */

import * as React from "react";
import { connect } from "react-redux";
import { IRootState, Dispatch } from "../../../../store";
import {
  Form,
  Table,
  Input,
  Button,
  Modal,
  Select,
  Divider,
  Popconfirm,
  message
} from "antd";

import { FormComponentProps } from "antd/lib/form";
import TitleCard from "src/components/TitleCard";
import TextArea from "antd/lib/input/TextArea";
import moment from "moment";

const mapStateToProps = ({ product, goods, loading }: IRootState) => ({
  product,
  goods,
  loading: loading.effects.product.getProductList as any
});
const mapDispatchToProps = ({ product, goods }: Dispatch) => ({
  getProductList: (payload: any) => product.getProductList(payload),
  editProduct: (payload: any) => product.editProduct(payload),
  getProductById: (payload: { id: string; callback?: any }) =>
    product.getProductById(payload),
  findByProId: (id: string) => goods.findByProId(id),
  deleteProduct: (id: string) => product.deleteProduct(id)
});

type connectedProps = ReturnType<typeof mapStateToProps> &
  ReturnType<typeof mapDispatchToProps>;

interface IState {
  visible: boolean;
  edit: boolean;
  searchValue: string;
  product: any;
  currPage: number;
}

interface IProps extends connectedProps {
  loading: boolean;
}

class ProductEdit extends React.Component<IProps & FormComponentProps, IState> {
  public state = {
    visible: false,
    edit: false,
    searchValue: "",
    product: "",
    currPage: 0
  };

  public componentDidMount = () => {
    const { getProductList } = this.props;
    getProductList({
      page: 0,
      size: 10,
      name: ""
    });
  };
  public handleSearch = () => {
    const { getProductList } = this.props;
    getProductList({
      // page: '0',
      size: 10,
      name: this.state.searchValue
    });
  };

  public inputChange = (e: any) => {
    this.setState({
      searchValue: e.target.value
    });
  };

  public handleOk = (e: any) => {
    const { editProduct } = this.props;
    e.preventDefault();
    this.props.form.validateFieldsAndScroll(async (err, values) => {
      if (!err) {
        await editProduct(values);
        this.setState({
          visible: false
        });
      }
    });
  };

  public handleCancel = () => {
    this.setState({
      visible: false
    });
  };

  public handleDetail = async (id: any) => {
    const { getProductById } = this.props;
    await getProductById({
      id,
      callback: (res: any) => {
        console.log(res);
      }
    });
    this.setState({
      visible: true
    });
  };

  public changePage(pageNumber: any, pageSize: any, props: any) {
    const { getProductList } = this.props;
    const payload = {
      name: this.state.searchValue,
      page: pageNumber - 1,
      size: pageSize
    };
    this.setState({
      currPage: pageNumber
    });

    getProductList(payload);
  }

  public async deleteHandle(id: string) {
    const { findByProId, deleteProduct } = this.props;
    await findByProId(id);
    const { goodProList } = this.props.goods;

    if (goodProList.length > 0) {
      message.warning("请先删除已绑定商品信息!");
      return;
    }

    deleteProduct(id);
  }

  public tableRender() {
    const { productList } = this.props.product;
    const { pageTotal } = this.props.product;
    const column = [
      {
        title: "序号",
        dataIndex: "seq",
        render: (text: any, record: any, index: any) => {
          return index + 1;
        }
      },
      {
        title: "产品名称",
        dataIndex: "name"
      },
      {
        title: "产品描述",
        dataIndex: "description"
      },
      {
        title: "状态",
        dataIndex: "status",
        render: (text: any, record: any, index: any) => {
          if (String(text) === "0") {
            return "未启用";
          } else {
            return "启用";
          }
        }
      },
      {
        title: "创建时间",
        dataIndex: "creatorTime",
        render: (text: any, record: any, index: any) => {
          return (
            <span>
              {text ? moment(text).format("YYYY-MM-DD HH:mm:ss") : " - -"}
            </span>
          );
        }
      },
      {
        title: "更新时间",
        dataIndex: "updateTime",
        render: (text: any, record: any, index: any) => {
          return (
            <span>
              {text ? moment(text).format("YYYY-MM-DD HH:mm:ss") : " - -"}
            </span>
          );
        }
      },
      {
        title: "操作",
        dataIndex: "",
        render: (text: any, record: any, index: any) => {
          return (
            <div>
              <Button
                type="primary"
                size="small"
                onClick={() => this.handleDetail(record.id)}
              >
                编辑
              </Button>

              <Divider type="vertical" />
              <Popconfirm
                title="确定要删除商品吗？"
                onConfirm={() => this.deleteHandle(record.id)}
                okText="确定"
                cancelText="取消"
              >
                <Button type="danger" size="small">
                  删除
                </Button>
              </Popconfirm>
            </div>
          );
        }
      }
    ];

    return (
      <Table
        dataSource={productList}
        columns={column}
        rowKey={"id"}
        pagination={{
          current: this.state.currPage,
          total: pageTotal,
          onChange: (page, size) => this.changePage(page, size, this.props)
        }}
      />
    );
  }

  public render() {
    const { getFieldDecorator } = this.props.form;
    const { productById } = this.props.product;
    return (
      <div className="message-container" style={{ paddingTop: 32 }}>
        <div style={{ marginLeft: "20px" }}>
          <b>产品名称:</b>
          <Input
            style={{ width: "200px", marginLeft: "10px" }}
            onChange={this.inputChange}
          />
          <Button
            type="primary"
            onClick={this.handleSearch}
            style={{ marginLeft: "10px" }}
          >
            查询
          </Button>
        </div>

        <TitleCard style={{ paddingTop: 32 }}>{this.tableRender()}</TitleCard>

        <Modal
          title={"编辑产品"}
          destroyOnClose={true}
          onOk={this.handleOk}
          onCancel={this.handleCancel}
          okText={"确定"}
          cancelText={"取消"}
          visible={this.state.visible}
        >
          <Form>
            <Form.Item
              label="产品名称"
              labelCol={{ span: 6 }}
              wrapperCol={{ span: 15 }}
              style={{ display: "none" }}
            >
              {getFieldDecorator("id", {
                initialValue: productById === null ? "" : productById.id,
                rules: [
                  {
                    required: false,
                    message: "请输入产品名称"
                  }
                ]
              })(<Input disabled={this.state.edit} />)}
            </Form.Item>

            <Form.Item
              label="产品名称"
              labelCol={{ span: 6 }}
              wrapperCol={{ span: 15 }}
            >
              {getFieldDecorator("name", {
                initialValue: productById === null ? "" : productById.name,
                rules: [
                  {
                    required: true,
                    message: "请输入产品名称"
                  }
                ]
              })(<Input disabled={this.state.edit} />)}
            </Form.Item>

            <Form.Item
              label="状态"
              labelCol={{ span: 6 }}
              wrapperCol={{ span: 15 }}
            >
              {getFieldDecorator("status", {
                initialValue:
                  productById === null ? "0" : String(productById.status),
                rules: [
                  {
                    required: true,
                    message: "请选择产品状态"
                  }
                ]
              })(
                <Select>
                  <Select.Option value="0">未启用</Select.Option>
                  <Select.Option value="1">启用</Select.Option>
                </Select>
              )}
            </Form.Item>

            <Form.Item
              label="产品描述"
              labelCol={{ span: 6 }}
              wrapperCol={{ span: 15 }}
            >
              {getFieldDecorator("description", {
                initialValue:
                  productById === null ? "" : productById.description,
                rules: [
                  {
                    required: true,
                    message: "请输入产品描述"
                  }
                ]
              })(<TextArea rows={10} cols={10} />)}
            </Form.Item>
          </Form>
        </Modal>
      </div>
    );
  }
}

export default connect(
  mapStateToProps,
  mapDispatchToProps
)(Form.create<IProps & FormComponentProps>({})(ProductEdit));
